package com.manage.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import com.manage.activity.BugIndexActivity;
import com.manage.activity.MainActivity;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class AppUtils {

	private static final String USER_AGENT = "User-Agent";

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(AppConstans.DATE_FORMAT);

	public static void logE(Throwable e) {
		Log.e(AppConstans.LOG_TAG, e.getMessage(), e);
	}

	public static void logI(String message) {
		Log.i(AppConstans.LOG_TAG, message);
	}

	public static String getMD5(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			logE(e);
			return null;
		} catch (UnsupportedEncodingException e) {
			logE(e);
			return null;
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}
	
	public static String httpPost(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		httpPost.setHeader(USER_AGENT, "Mozilla/4.5");
		HttpEntity httpEntity = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			httpEntity = httpclient.execute(httpPost).getEntity();
		} finally {
			httpPost.abort();
		}
		return retrieveHttpEntity(httpEntity);
	}

	public static String httpPost(String url) throws ClientProtocolException, IOException {
		return httpPost(url, new ArrayList<NameValuePair>());
	}

	private static String retrieveHttpEntity(HttpEntity httpEntity) throws UnsupportedEncodingException, IllegalStateException,
			IOException {
		StringBuffer stringBuffer = new StringBuffer();
		InputStreamReader is = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
		BufferedReader bufferedReader = new BufferedReader(is);
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line);
		}
		return stringBuffer.toString();
	}

	public static String formatDate(Date date) {
		return dateFormat.format(date);
	}

	/**
	 * String format: yyyy-MM-dd HH:mm:ss(e.g. 2011-05-01 00:00:00)
	 * 
	 * @param dateString
	 * @return
	 * @throws ParseException
	 */
	public static Date parseStringToDate(String dateString) throws ParseException {
		return dateFormat.parse(dateString);
	}

	/**
	 * 产生一个6位随机数
	 * 
	 * @return 随机数
	 */
	public static String getRandomNumber() {
		int ran = (int) ((Math.random() * 1000000));
		String random = String.valueOf(ran);
		int temp = random.length();
		if (temp == 6)
			return random;
		temp = AppConstans.RANDOM_LENGTH - temp;
		random = AppConstans.RANDOM_LENGTH_NUMBER.substring(0, temp) + random;
		return random;
	}

	public static String getMobileModel() {
		return Build.BOARD + " " + Build.BRAND + " " + Build.DEVICE;
	}

	/**
	 * 
	 * 判断网络状态是否可用
	 * 
	 * @return true: 网络可用 ; false: 网络不可用
	 */
	public static boolean isNetworkConnected(Activity activity) {
		ConnectivityManager conManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
		if (networkInfo != null) { // 这个判断一定要，要不然会出错
			return networkInfo.isAvailable();
		}
		return false;
	}

	/**
	 * 判断正则管则的函数
	 * 
	 * @param mString
	 *            要进行判断的字符串
	 * @param mPattern
	 *            要对字符串进行哪一种判断
	 * @return 判断结果：true or false
	 */
	public static boolean isRegular(String mString, String mPattern) {
		Pattern p = Pattern.compile(mPattern);
		Matcher m = p.matcher(mString);
		return m.matches();
	}

	/**
	 * 判断一个service是否在运行
	 * 
	 * @param context
	 * @param c
	 * @return
	 */
	public static boolean isServiceRunning(Context context, Class<?> c) {
		ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString().equals(c.getName().toString())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 通过GPS得到城市名
	 * 
	 * @param context
	 *            一個Activity
	 * @return 城市名
	 */
	public static String getCityName(Context context) {
		LocationManager locationManager;
		String contextString = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) context.getSystemService(contextString);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(false);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String cityName = null;
		// 取得效果最好的criteria
		String provider = locationManager.getBestProvider(criteria, true);
		if (provider == null) {
			return cityName;
		}
		// 得到坐标相关的信息
		Location location = locationManager.getLastKnownLocation(provider);
		if (location == null) {
			return cityName;
		}

		if (location != null) {
			double latitude = location.getLatitude();
			double longitude = location.getLongitude();
			// 更具地理环境来确定编码
			Geocoder gc = new Geocoder(context, Locale.getDefault());
			try {
				// 取得地址相关的一些信息\经度、纬度
				List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
				StringBuilder sb = new StringBuilder();
				if (addresses.size() > 0) {
					Address address = addresses.get(0);
					sb.append(address.getLocality()).append("\n");
					cityName = sb.toString();
				}
			} catch (IOException e) {
			}
		}
		return cityName;
	}

	public static String encode(String s) throws UnsupportedEncodingException {
		return URLEncoder.encode((s == null ? "" : s), AppConstans.UTF_8);
	}
	
	public static DisplayMetrics getDisplayMetrics(Activity context) {
		DisplayMetrics dm = new DisplayMetrics();
		context.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm;
	}
	

	private static String TAG = "@@@";
	private static int RANDOM_LENGTH = 6;
	private static String RANDOM_LENGTH_NUMBER = "";

	static {
		for (int i = 0; i < RANDOM_LENGTH; i++) {
			RANDOM_LENGTH_NUMBER = RANDOM_LENGTH_NUMBER + "0";
		}
	}

	public static void makeToast(String str, boolean isLong, Context context) {
		if (isLong == true) {
			Toast.makeText(context, str, Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
		}
	}

	public static void makeToast(String str, Context context) {
		makeToast(str, false, context);
	}


	public static String getMD5(String str, String encode) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes(encode));
		} catch (NoSuchAlgorithmException e) {
			logE(e);
			return null;
		} catch (UnsupportedEncodingException e) {
			logE(e);
			return null;
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}

	
	

	public static byte[] readFile(String filename) throws IOException {
		BufferedInputStream bufferedInputStream = null;
		try {
			bufferedInputStream = new BufferedInputStream(new FileInputStream(filename));
			int len = bufferedInputStream.available();
			byte[] bytes = new byte[len];
			int r = bufferedInputStream.read(bytes);
			if (len != r) {
				bytes = null;
				throw new IOException("读取文件不正确");
			}
			return bytes;
		} finally {
			close(bufferedInputStream);
		}
	}

	public static void close(Closeable c) {
		if (c != null) {
			try {
				c.close();
			} catch (IOException e) {
				// do nothing.
			}
		}
	}

	
}
